// package_shop/pages/product-order/product-order.js
import Api from '../../../utils/http/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    count: '',//下单数量
    address: '请选择',//收货地址
    date: '请选择',//配送时间
    total: '',//总价
    invoice: '',//发票
    remark: '',//备注

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let product = JSON.parse(options.product)
    let count = options.count
    var total = count * product.price;

    this.setData({
      product,
      count,
      total,
    })

    this.setData({

      total: total
    })
  },

  //获取地址
  bindAddressChange: function (e) {
    console.log(1111111111111111);
    wx.chooseAddress({
      success: res => {
        console.log('获取地址=res',res);
        this.setData({
          address: res
        })
      },
    })
  },

  //获取日期
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  //获取订单备注中的数据
  bindRemarkInput: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },

  //获取订单备注中的数据
  bindInvoiceInput: function (e) {
    this.setData({
      invoice: e.detail
    })
  },
  // 通用弹窗 打开
  onShowPopup() {
    this.selectComponent('#wDialog').onShowPopup()
  },
  // 通用弹窗 关闭
  onHidePopup() {
    this.selectComponent('#wDialog').onHidePopup()
  },
  // 确定 弹窗回调
  onConfirm() {
    this.onHidePopup()
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  onPay() {
    if (!getApp().globalData.loginFlag) {
      wx.navigateTo({
        url: `/pages/login/login`
      })
      return
    }
    //完成订单的创建
    var pid = this.data.product.pid;
    var count = this.data.count;
    var address = this.data.address;
    var shippingTime = this.data.date;
    var invoice = this.data.invoice;
    var remark = this.data.remark;


    if (address && address.length < 6) {
      wx.showToast({
        title: '请选择地址！',
        icon: 'none',
        duration: 3000
      })
      return;
    }
    address = address.cityName + ',' + address.detailInfo + ',' + address.userName + ',' + address.telNumber
    if (shippingTime == '请选择') {
      shippingTime = null
      wx.showToast({
        title: '请选择配送时间！',
        icon: 'none',
        duration: 3000
      })
      return;
    }

    this.createOrder(address)
  },
 //创建订单接口
  createOrder(address) {
    let params = {
      pid: this.data.product.pid,
      count: this.data.count,
      address: address,
      shippingTime: this.data.date,
      invoice: this.data.invoice,
      remark: this.data.remark,

    }
    Api.createOrder(params).then(res => {
      this.onShowPopup()

    }).catch(err => console.log(err))
  }
})
